package cn.springcloud.fix.demo.leecode;

import java.util.HashSet;
import java.util.Set;

public class HasCycle {

    /**
     * 判断是否是环链
     */
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node2);
        boolean sus = hasCycle3(node1);
    }

    //判断是否是环链
    private static boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (!set.add(head)) {
                return true;
            }
            head = head.getNext();
        }
        return false;
    }

    //判断是否是环链
    private static boolean hasCycle2(ListNode head) {
        if (head == null || head.getNext() == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.getNext();
        while (slow != fast) {
            if (fast == null || fast.getNext() == null) {
                return false;
            }
            slow = slow.getNext();
            fast = fast.getNext().getNext();
        }
        return true;
    }

    //判断是否是环链
    private static boolean hasCycle3(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.getNext();
        while (fast != null && fast.getNext() != null) {
            if (slow == fast) {
                return true;
            }
            slow = slow.getNext();
            fast = fast.getNext().getNext();
        }
        return false;
    }
}
